//logs.js
const util = require('../../utils/util.js')
const mockData = require('../../config/mock/data.js')
import common from '../../config/js/common';

var innerAudioContext
var currentPage

Page({
  data: {
    today: '',
    imageSrc: "/image/laba.png",
    status: "0",
    stayDays: '',
    poem: {}
  },
  onLoad: function () {
    let Pages = getCurrentPages()
    currentPage = Pages[Pages.length - 1]

    let token = wx.getStorageSync('token')
      wx.request({
        url: common.user_center + "index",
        method: 'GET',
        header: {
          'WX-TOKEN': token
        },
        data: { token: token },
        success(res) {
          let data = res.data;
          console.log("请求主页数据 后台返回")
          console.log(data)
          // 服务端登录注册成功
          if (data.code == 0) {
            let indexData = data.data
            currentPage.setData({
              today: indexData.today,
              stayDays: indexData.stayDays,
              poem: indexData.poem
            })
            currentPage.initMP3()
          }
        },
        fail(res) {
          console.log("请求主页数据 服务调用异常：" + res)
        },
      })
  },
  onHide: function () {
    this.destroyMP3()
  },
  onUnload: function () {
    this.destroyMP3()
  },
  onShow: function(){
    this.initMP3()
  },
  onTabItemTap: function(){
    this.initMP3()
  },
  learnRead: function (event) {
    let status = event.currentTarget.dataset.status
    if (status == "0") { // 停止状态
      this.setData({
        imageSrc: "/image/zanting.png",
        status: "1"
      })
      innerAudioContext.play()
    } else if (status == "1") {
      this.setData({
        imageSrc: "/image/laba.png",
        status: "0"
      })
      innerAudioContext.pause()
    }
  },
  writePoem: function (event) {
    let token = wx.getStorageSync('token')
    if (token){
      common.openConfirm("确定已背会，尝试默写吗？", "绝不偷看", "算了",
        function () {
          wx.navigateTo({
            url: '/pages/recite/recite?id=' + currentPage.data.poem.id + '&title=' + currentPage.data.poem.title,
          })
        })
    }else{
      wx.switchTab({
        url: '/pages/my/my'
      })
    }
  },
  toView: function (event) {
    wx.navigateTo({
      url: '/pages/appreciation/appreciation?poemId=' + currentPage.data.poem.id
    })
  },
  learnCreate: function (event) {
    console.log(event)
  },
  initMP3: function () {
    innerAudioContext = wx.createInnerAudioContext()
    innerAudioContext.autoplay = false
    let mp3src = common.mp3_url + this.data.poem.mp3
    innerAudioContext.src = mp3src
  },
  destroyMP3: function (){
    innerAudioContext.destroy()
    this.setData({
      imageSrc: "/image/laba.png",
      status: "0"
    })
  },
  onPullDownRefresh: function () {
    this.onLoad()
  }
})
